<template>
  <div class='q-pa-md'>
    <q-table
      title='Treats'
      :rows='rows'
      :columns='columns'
      row-key='id'
      :pagination='initpagination'
      :loading='loading'
      :filter='filter'
      @request='onRequest'
      binary-state-sort
    >
      <template v-slot:top-left>
        <div class='row'>
          <div class='col-4' style='min-width: 250px; max-width: 300px' @mouseover='mouseover'>
            <q-select
              filled
              v-model='mulSelect.arr'
              multiple
              use-chips
              stack-label
              label='选择项'
              name='search'
            />
          </div>
          <div class='col-2'>
            <q-btn color='white' text-color='black' icon='search' @click='fetchFromServer' />
          </div>
        </div>

        <div class='q-pt-md row justify-start items-center'>
          <div class='q-px-md' v-for='(item,index) in searchFrame' :key='index'>
            <q-btn-dropdown class='col-4' color='primary' :label='item.property_name'
                            @click='onQueryBar(index+1)'>
              <q-list v-for='item in searchFrameArr' :key='item.markNo'>
                <q-item clickable v-close-popup @click='searchClick(item,index)'>
                  <q-item-section>
                    <q-item-label>
                      {{ item.value }}
                    </q-item-label>
                  </q-item-section>
                </q-item>
              </q-list>
            </q-btn-dropdown>
          </div>
        </div>

      </template>
      <template v-slot:top-right>
        <q-btn v-for='(item,index) in globalOperation' :key='index' color='primary' :label='item' class='control-btn' />
      </template>
      <template v-slot:header='props'>
        <q-tr :props='props'>
          <template
            v-for='col in props.cols'
            :key='col.name'
            :props='props'
          >
            <template v-if='col.name == "control"'>
              <q-th align='left' class='sticky-col'>
                {{ col.label }}
              </q-th>
            </template>
            <template v-else>
              <q-th align='left'>
                {{ col.label }}
              </q-th>
            </template>
          </template>
        </q-tr>
      </template>
      <template v-slot:body='props'>
        <q-tr :props='props'>
          <template
            v-for='col in props.cols'
            :key='col.name'
            :props='props'>
            <template v-if='col.name == "control"'>
              <q-td class='sticky-col'>
                <q-btn-dropdown
                  split
                  :label='operationFirstSelections'
                >
                  <q-list v-for='(item, index) in operationSelections' :key='index'>
                    <q-item clickable v-close-popup @click='onItemClick'>
                      <q-item-section>
                        <q-item-label>{{ item }}</q-item-label>
                      </q-item-section>
                    </q-item>
                  </q-list>
                </q-btn-dropdown>
              </q-td>
            </template>
            <template v-else>
              <q-td>
                {{ col.value }}
              </q-td>
            </template>
          </template>
        </q-tr>
      </template>
    </q-table>
  </div>
</template>
<script lang='ts'>
import {
  ChannelRouteQuery,
  Column,
  Meta,
  Operation,
  OriginalRows,
  Pagination,
  Props,
  ResData,
  TableColumn,
  Todo
} from 'src/components/models';
import { ref, onMounted, defineComponent, PropType, reactive } from 'vue';
import { getRequest, postRequest } from '../components/functions';
import { useStore } from 'src/store';
import { useRoute, useRouter } from 'vue-router';
import { api } from 'boot/axios';

export default defineComponent({
  name: 'TableComponent',
  setup(props) {
    let rote = useRoute();
    let router = useRouter();
    const getInterface = '/channel/channel/getInterface';
    const queryMenu = 'channel/channel/queryMenu';
    const userData = useStore().state.sphinx.userData;
    const updateApiState = useStore().state.sphinx.api;
    let columns = ref<TableColumn[]>();
    let operationFirstSelections = ref<string>();
    let operationSelections = ref<string[]>();
    let globalOperation = ref<string[]>();
    const originalRows = ref<OriginalRows[]>();
    let fromdataUrl = ref<string>('');
    const rows = ref([]);
    const filter = ref<string>();
    const loading = ref<boolean>(true);
    const pagination = ref<Pagination>({
      sortBy: 'desc',
      descending: false,
      page: 1,
      rowsPerPage: 10,
      rowsNumber: 10
    });
    let entityCode = ref(rote.query.entityCode);
    let childCode = ref<string>('');
    let mulSelect = reactive({ arr: [] });
    let QueryBarCode = reactive({ arr: [] });
    // let searchBar = ref<boolean>(false);
    let searchFrame = ref([]);
    let searchFrameArr = ref([]);

    //点击下拉的数据展示在搜索框里
    function searchClick(item: any, index: number) {
      let itemElement = searchFrame.value[index].property_code;
      mulSelect.arr.push(item.value);
      let obj = {};
      obj[itemElement] = item.value;
      QueryBarCode.arr.push(obj);
      mulSelect.arr = Array.from(new Set(mulSelect.arr));
    }

    // 点击下拉搜索框获取下拉的数据
    function onQueryBar(i) {
      //获取搜索数据的接口
      let resData = {
        entityCode: entityCode.value,
        entityType: childCode.value + '1070' + i,
        theirEventCode: '001'
      };
      let QueryBarUrl = ref<string>('');
      postRequest(getInterface, resData, res => {
        let url=res.data.interfaceEnglish;
        QueryBarUrl.value=url.substr(url.indexOf('/')+1)
      });

      //获取搜索条件
      let resData1 = {
        entityCode: entityCode.value,
        entityType: childCode.value,
        sceneCodeType: '101102' + userData.roleType + '103',
        objectCodeType: '1070' + i
      };
      let QueryBarData = ref({});
      postRequest(queryMenu, resData1, res => {
        res.forEach(i => {
          let obj = {};
          obj[i.property_code] = '';
          QueryBarData.value = obj;
        });
      });

      //获取搜索数据
      searchFrameArr.value = [];
      setTimeout(() => {
        postRequest(QueryBarUrl.value, QueryBarData.value, res => {
          searchFrameArr.value = res;
        });
      }, 1000);
    }

    /**s
     * 请求类型列名
     */
    async function requestColumns() {
      let sceneCode = await getSceneCode();
      let reqData = reactive({});
      if (entityCode.value != undefined) {
        reqData = {
          companyId: userData.companyId,
          entityCode: entityCode.value,
          entityType: childCode.value,
          sceneCode: sceneCode,
          objectCodeType: '102'//主体首页表头
        };
      }
      postRequest(queryMenu, reqData, getColums);
    }

    /**
     * 设置类型列名
     * @param resultData
     */
    function getColums(resultData:any) {
      console.log('获取类型表头数据', resultData);
      let newArr = [];
      if (resultData !== undefined && resultData !== null && resultData.length > 0) {
        resultData.forEach(item => {
          newArr.push({ name: item.property_code, label: item.property_name, field: item.property_code });
        });
      }
      columns.value = newArr;
      console.log(columns.value);
    }

    /**
     * 请求表内数据
     * @param startRow
     * @param count
     * @param filter
     * @param sortBy
     * @param descending
     */
    function fetchFromServer(startRow: number, count: number, filter: string, sortBy: string, descending: boolean) {
      //处理搜索内容的数据
      let newArr = ref([]);
      QueryBarCode.arr.forEach(x => {
        mulSelect.arr.forEach(y => {
          if (y == Object.values(x)[0]) {
            newArr.value.push(x);
          }
        });
      });
      let target = ref({});
      if (newArr.value.length != 0) {
        newArr.value.forEach(item => {
          Object.assign(target.value, item);
        });
      }

      postRequest(fromdataUrl.value, target.value, res => {
        rows.value = res;
        loading.value = false;
      });

      // getRequest(fromdataUrl.value, (data) => {
      //   searchBar.value = false;
      //   // searchFrame.value.length = 0;
      //   // mulSelect.arr.length = 0;
      //   rows.value = data;
      // }, target.value);
    }

    // 获取请求表内数据的接口
    function getFromdataUrl() {
      let data = {
        entityCode: entityCode.value,
        entityType: childCode.value,
        theirEventCode: '001'
      };
      postRequest(getInterface, data, res => {
        let url=res.data.interfaceEnglish;
        fromdataUrl.value=url.substr(url.indexOf('/')+1)
        onRequest({
          pagination: pagination.value,
          filter: ''
        });
      });
    }

    /**
     * 计算分页
     * @param filter
     */
    function getRowsNumberCount(filter: string): number {
      let count = 0;
      if (originalRows.value !== undefined) {
        if (!filter) {
          return originalRows.value.length;
        }
        originalRows.value.forEach((treat: OriginalRows) => {
          if (treat.name.includes(filter)) {
            ++count;
          }
        });
      }
      return count;
    }

    /**
     * 数据请求
     * @param props
     */
    function onRequest(props: Props) {
      const { page, rowsPerPage, sortBy, descending } = props.pagination;
      const filter = props.filter;
      // emulate server
      setTimeout(() => {
        // update rowsCount with appropriate value
        pagination.value.rowsNumber = getRowsNumberCount(filter);
        // get all rows if "All" (0) is selected
        const fetchCount = rowsPerPage === 0 ? pagination.value.rowsNumber : rowsPerPage;
        // calculate starting row of data
        const startRow = (page - 1) * rowsPerPage;
        // fetch data from "server"
        fetchFromServer(startRow, fetchCount, filter, sortBy, descending);
        // clear out existing data and add new
        // don't forget to update local pagination object
        pagination.value.page = page;
        pagination.value.rowsPerPage = rowsPerPage;
        pagination.value.sortBy = sortBy;
        pagination.value.descending = descending;
        // ...and turn of loading indicator
      }, 10);
    }

    // 鼠标放在搜索框上出搜索选项
    async function mouseover() {
      let scene = await getSceneCode()
      let resData = {
        companyId: userData.companyId,
        entityCode: entityCode.value,
        entityType: childCode.value,//类型代码为00
        sceneCode: scene,
        objectCodeType: '107'//代表搜索的代码
      };
      if (searchFrame.value.length == 0) {
        postRequest(queryMenu, resData, (res: []) => {
          searchFrame.value = res;
          // searchBar.value = true;
        });
      }
    }


    function getSceneCode(){
      let requestSceneBody = [
        {
          "entityCode":'101',
          "codeName":'',
          "entityType":'01',
          "typeName":'',
          "eventCode":null,
          "eventName":null,
          "propertyEnglish":null,
          "propertyChinese":null,
          "propertyValue":null,
          "propertyCondition":null,
          "companyId":userData.companyId
        },
        {
          "entityCode":'102',
          "codeName":'',
          "entityType":'02',
          "typeName":'',
          "eventCode":null,
          "eventName":null,
          "propertyEnglish":'roleType',
          "propertyChinese":null,
          "propertyValue":userData.roleType,
          "propertyCondition":null,
          "companyId":userData.companyId
        }];
      return new Promise((resolve,reject)=>{
        api.post('/channel/channel/getSceneCode',requestSceneBody).then(res=>{
          resolve(res.data.data);
        }).catch(err=>{
          reject(err);
        })
      });
    }

    /**
     * 通过地址栏获取传来的实体代码entityCode
     */
    function setApiByInterfaceEnglish() {
      entityCode.value = <string>rote.query.entityCode;
      childCode.value = <string>rote.query.childCode;
      if (childCode.value === undefined) {
        childCode.value = '';
      }
    }

    /**
     * 组合请求
     */
    function requestTableData() {
      setApiByInterfaceEnglish();
      requestColumns();//请求列名
      // get initial data from server (1st page)
      getFromdataUrl();
      //获取接口，在下面获取表内数据
    }

    onMounted(() => {
      requestTableData();//组合请求
    });
    return {
      getSceneCode,
      filter,
      loading,
      pagination,
      columns,
      rows,
      operationFirstSelections,
      operationSelections,
      globalOperation,
      onRequest,
      entityCode,
      updateApiState,
      getFromdataUrl,
      fromdataUrl,
      mouseover,
      setApiByInterfaceEnglish,
      mulSelect,
      // searchBar,
      searchFrame,
      searchFrameArr,
      onQueryBar,
      searchClick,
      childCode,
      fetchFromServer,
      initpagination: {
        sortBy: 'desc',
        descending: false,
        page: 2,
        rowsPerPage: 10
        // rowsNumber: xx if getting data from a server
      },
    };
  }
});
</script>
<style scoped lang='sass'>
.control-btn
  padding-left: 1em
  padding-right: 1em
  margin: 0.5em

.sticky-col
  position: sticky
  right: 0
  z-index: 1
  background-color: white
</style>
